/** @jsxImportSource @emotion/react */
import * as React from "react";
//import {useDispatchTaskTo, useDispatchToLiabler, useDispatchToOffice, usePaginateQueryTask} from "./db";

import {
    IconButton,
    Text, Stack, StackItem,
    useTheme,
    Spinner,
    IconPackage,
    Dialog,
    InputLine,
    Button,
    Input,
    useResponsiveContainerPadding,
    InputGroup,
    CommitInput,
    IconSearch,
    IconLayers,
    useMMenuBarOcup,
    Navbar,
    Toolbar,
    DdMenu,
    DdMenuItem,
    VerticalMenu,
    DialogHeading,
    DialogContent,
    DialogDescription,
    DialogClose
} from "customize-easy-ui-component";

//import { StackItem,  } from "react-gesture-stack";
import {usePaginationFragment, useRefetchableFragment} from "react-relay/hooks";
// import {OneAgreementWraper$data, OneAgreementWraper$key} from "./__generated__/OneAgreementWraper.graphql";
import {SyntheticEvent, useContext, useEffect} from "react";
// import { BoundDevices } from "./BoundDevices";
// import useDispatchTaskToMutation from "./useDispatchTaskToMutation";
// import useCancellationTaskMutation from "./useCancellationTaskMutation";
// import useSummaryTaskFeeMutation from "./useSummaryTaskFeeMutation";

import RoutingContext from "../routing/RoutingContext";
import {FlowReportConfig} from "../inspect/report/FlowReportConfig";
import {getReportModelTypes} from "../inspect/report/reportTypeMap";
import UserContext from "../routing/UserContext";
// import {TaskLikeData, useLiablerDialogMenu, useOfficeDialogMenu} from "./useHelpers";
// import {taskStatusMap} from "./TaskList";
import {css} from "@emotion/react";
import {businessTypeMap} from "../device/edit/CommnBase";
// import useFinishTaskMutation from "./useFinishTaskMutation";
import {AgreementBoundDevices} from "./AgreementBoundDevices";
import {agreementStatusMap} from "./AgreementList";
import {OneAgreementMainQuery$data} from "./__generated__/OneAgreementMainQuery.graphql";
import {RefetchFnDynamic} from "react-relay/relay-hooks/useRefetchableFragmentNode";
import useBuildAgreementMutation from "./hook/useBuildAgreementMutation";
// import {Stack, StackItem} from "../../UiDebugSave/sample/Stack";

//只能在内容的顶部下拉，才能触发的，还是需要快捷的按钮。 淘汰掉，鸡勒了也不好用告警。
//import { PullDownContent, PullToRefresh, RefreshContent, ReleaseContent } from "react-js-pull-to-refresh";
//import { BoundDevices } from "./BoundDevices";
//import { useDeleteReport } from "../../inspect/report/db";
const graphql = require("babel-plugin-relay/macro");

export interface OneAgreementWraperProps {
    //这个类型不能乱来，TS编译要用，底下的data要看这个: 返回graphql模型字段定义了吗;
    //正常REF模式是  modref: OneAgreementWraper$key;
    agreement: OneAgreementMainQuery$data["node"];
    //只能这样声明 泛型的 类型了：
    refetch: RefetchFnDynamic<any, any>;
}
/**不管哪一种类的协议申请单：都有这样的常用字段结构，关联设备列表。
 * */
export const OneAgreementWraper: React.FunctionComponent<OneAgreementWraperProps>
    = ({agreement, refetch}) => {
    //第一次啊运行吗？
    const mountedRef = React.useRef(0);
    if(!mountedRef.current) {
        mountedRef.current = 1;
    }
    else
        mountedRef.current++;
    //后面refetch:实际是 (vars: TVars, options?: TOptions) => Disposable;的回调函数。
    // const [data, refetch] = useRefetchableFragment(
    //     graphql`
    //         fragment OneAgreementWraper on Query
    //         @refetchable(queryName: "OneAgreementWraperRefetchQuery") {
    //             node(id: $modId)
    //             {
    //                 id, __typename,
    //                 ... on Agreement {
    //                     id,ptno,status,servu{id,name}
    //                     dispatcher{id,dep{id,name},office{id,name}},complDate,aux
    //                     ...AgreementBoundDevices
    //                 }
    //             }
    //         }
    //     `,
    //     props.modref,
    // );
    console.log("来OneAgreementWraper看当前的data=",agreement );
    // const agreement= props.agreement;
    // @ts-ignore
    const details = agreement?.detail_list?.edges?.map(edge => edge?.node);
    const typicisp = details && details.length>0 && details[0]?.isp;         //典型Isp
    const {user} = useContext(UserContext);
    const  aux = JSON.parse(agreement?.aux || '{}');        //特别处理 依赖反转。
    const theme = useTheme();
    //提取生成关联的数据Task-Detail[0]-Isp-Report-stm-author[]；检验员人员初始化依据第一个Isp设备的主报告而定。做个短路ApprovalStm快捷访问。
    const [query, ] = React.useState("");
    //const [relation, setRelation] = React.useState();

    const [, setFilter] = React.useState({where:
            {cod:query },
    });

    const noUsers = !query && !agreement;
    //下层沉下去的 setIndex切换显示界面；
    const [index, setIndex] = React.useState(0);


    /*
    const { submit:dispatch2liablFunc, } = useDispatchToLiabler({
        task: relation, liabler: 1
    });
    //发后端verify:{id:1,username:'herzhang'},后端实体User(String name){}会直接构造输入参数，把{id=1, username=herzhang}当成name构造User
    const { submit:dispatch2TaskFunc, } = useDispatchTaskTo({
        task: relation,date:'2021-02-09', verify:1, ispmen:[21,1,16]
    });
    */
    const {call:deleteAgreementFunc,doing,called, result}= useBuildAgreementMutation();
    // const {call:dispatch2TaskFunc,doing:doing2 }= useDispatchTaskToMutation();
    // const {call:cancelTaskFunc,doing:canceling, called, reset}= useCancellationTaskMutation();
    const { history } = useContext(RoutingContext);

    // const {call:summaryTaskFeeFunc,doing:summing,called:summed, result:summrs}= useSummaryTaskFeeMutation();
    // const {call:finishTaskFunc, }= useFinishTaskMutation();


    React.useEffect(() => {
        //console.log("伪善setQueryResul02=" ,query,usersFind);
        let filtercomp={where:
                {cod:query },
            offset:0,
            first:5,
            orderBy: "useDt",
            asc: false
        };
        setFilter(filtercomp);
    }, [query]);
    //这两个useEffect的前后顺序不能颠倒，顺序非常重要，后面的依赖于前面的useEffect更新结果。
    //usersFind=搜索框搜到到的user;
    /*切换到Stack的第一层*/
    // useEffect(() => {
    //     if(!canceling && called) {
    //         console.log("取消后端有了应答！-taskId=");
    //         //同步化处理机制，等待后端真正应答了，才能更新页面，否则继续等待。
    //         //setRelation(undefined);
    //         setIndex(0);
    //         reset();    //setCalled=false,导致不会再次运行上面这段;
    //     }
    //    //return () => dispose();
    // }, [canceling, called,reset]);

    //三个命令各自的配置模态对话框显示？
    // const [diaLiab, setDiaLiab] = React.useState(false);
    // const [master, setMaster] = React.useState<any>(agreement?.typicstm?.master);         //就是报告校核人
    // const [ispMens, setIspMens] = React.useState<any>(agreement?.typicstm?.authr);         //多个 检验人员[User];
    // const [reviewer, setReviewer] = React.useState<any>(agreement?.typicstm?.reviewer);    //审核人
    // const [approver, setApprover] = React.useState<any>(agreement?.typicstm?.approver);    //审批人
    const [modeltype, setModeltype] = React.useState<any>( 'EL-DJ' );
    const [modelversion, setModelversion] = React.useState<any>( '1' );
    // const [taskDate, setTaskDate] = React.useState<any>(agreement?.date);

    // const {menu: officeItem, dialog: officeDlg}= useOfficeDialogMenu(task! as TaskLikeData);
    // const {menu: liablerItem, dialog: liablerDlg}= useLiablerDialogMenu(task! as TaskLikeData);
    //一个任务底下#多个设备 单一次检验 设备种类典型的品种？ 可能有多种报告模板类型啊？？不能非常确定！全部依照典型设备来做，后面可改。
    //会有多次的render经过这里，每一回都会要求执行里面的计算啊， 【提高性能考虑】改成useMemo保存;
    const models =React.useMemo(() => getReportModelTypes('41','413','','REGUL',true), []);
    //上面这个副作用必须 加usersFind，否则无法继续处理后端数据带来的必要的UI反馈变化。
    const {barHeight } = useMMenuBarOcup(history.routeData?.isExact);
    //控件<Stack 是堆叠式的，像导航条；适用同一个模板显示只需上级给下级参数调整的场景。根据上一叠页面选择触发状态relation给下一叠参数来控制下一级显示；更多嵌套很困难。
    // if(canceling)
    //     return (
    //         <div style={{
    //                 display: "flex",
    //                 height: '87vh'
    //             }}
    //         >
    //           <Spinner doing={canceling} css={{margin: 'auto'}}/>
    //         </div>
    //     );
    //   console.log("点击触发 为何出2回:diaLiab=",diaLiab);
    //对话框和点击弹出遭遇可能要延迟 onPress= setTimeout(() => { setDisplayDialog(true); }, 0)避免点透点穿 自动关闭;
    //底下：禁止显示導航條disableNav； 只能是固定值navHeight，是依赖父辈的<Stack>传递context给儿孙<StackTitle>
    //这里<Stack  只有一层的，还没有标题工具条：实际等于摆设。
    //多套上一层DIV增加独立控制布局的能力； margin: auto;简易的遭遇小尺度内容的可屏幕居中显示。
    return (
        <React.Fragment>
            <div css={{
                margin: 'auto',
                background: 'white',
            }}>
                <div
                    css={{
                        width:'100%',
                    }}
                >
                    <Navbar  position="sticky"
                             css={{
                                 backgroundColor: "white",
                             }}
                    >
                        <Toolbar
                            css={{
                                alignItems: "center",
                                display: "flex",
                                minHeight: `${barHeight}`,
                                [theme.mediaQueries.lg]: {
                                    minHeight: `${barHeight}`,
                                }
                            }}
                        >
                            <Text
                                css={{
                                    flex: 1,
                                    textAlign: "center",
                                    [theme.mediaQueries.md]: {
                                        textAlign: "left"
                                    }
                                }}
                                wrap={false}
                                variant="h5"
                                gutter={false}
                            >
                                {`${agreement?.servu?.name}`}
                            </Text>
                            <VerticalMenu>
                                <DdMenuItem label="刷新本协议" onPress={() => refetch({first:4,},
                                    {fetchPolicy: "network-only"})}
                                />
                                <DdMenuItem label="生成协议附属任务"
                                            onPress={() => {
                                                history.push("/agreement/"+agreement?.id+'/'+agreement?.pttype+'/addTask');
                                            }} />
                                <DdMenuItem label="删除本协议" onPress={() => {
                                    //删除协议前提：要取消全部任务@；刚刚取消任务就点击已关联任务页面报错: 【后端缓存原因】导致不同步的短期报错。
                                    deleteAgreementFunc(agreement?.id!, 'DEL',{});
                                }} />
                            </VerticalMenu>
                        </Toolbar>
                    </Navbar>
                    <div css={{ marginLeft:'0.5rem', marginTop:'1rem',
                        backgroundColor: agreement?.status==='DONE'? 'pink': 'transparent',
                    }}>
                        <Text variant="h6">{`${agreementStatusMap.get(agreement?.status!) || '新'}`} {agreement?.dispatcher?.dep?.name || '?'} {agreement?.complDate}</Text>
                        <Text variant="h6">责任人：{agreement?.dispatcher?.person?.name || '#'}</Text>
                        <Text variant="h6">申请创建者：{agreement?.crman?.person?.name || '$'}</Text>
                        <Text variant="h6">{aux?.服务内容}</Text>
                        <Text variant="h6">关联的设备如下：</Text>
                    </div>
                </div>

                <Stack
                    navStyle={css({ position: 'sticky',  top: 0,})}
                    style={{
                        overflow: 'unset'
                    }}
                    index={index} disableNav={true} navHeight={40}
                    onIndexChange={i => setIndex(i)}
                    items={[
                        {
                            content: (
                                <StackItem className="ItemConte"
                                           css={{
                                               // marginBottom: `${barHeight}`,
                                           }}
                                           style={{ position: undefined, boxShadow:undefined }}
                                >
                                    <div className="DlistInnerF1"
                                         css={{overflowY: "auto", height: "100%",}}
                                    >
                                        {agreement && (
                                            <AgreementBoundDevices key={agreement?.id} task={agreement!} id={agreement?.id!} />
                                        )}
                                    </div>
                                </StackItem>
                            )
                        }
                    ]}/>
            </div>

        </React.Fragment>
    );
};

